package com.zhouqinuan.spring.cloud.develop.framework.base.util;

import java.io.UncheckedIOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.lang3.StringUtils;

public class IpUtil {

    /**
     * 获取本机服务器IP 
     */
    public static String getLocalIP() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                
                if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint()
                        || !netInterface.isUp()) {
                    
                    continue;
                }
                
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    
                    if (ip != null && ip instanceof Inet4Address) {
                        break;
                    }
                }
            }
            
            return ip == null ? "127.0.0.1" : StringUtils.isEmpty(ip.getHostAddress()) ? "127.0.0.1" : ip.getHostAddress();
            
        } catch (SocketException e) {
            throw new UncheckedIOException(e);
        }
    }
}
